import os
import shutil

def merge_and_clean():
    # 获取U盘路径
    usb_path = 'E:/'
    print(usb_path)
    if not os.path.exists(usb_path):
        print("错误：路径不存在。")
        return

    # 验证路径格式
    if not usb_path.endswith(('/', '\\')):
        usb_path += os.sep

    # 获取所有txt文件
    txt_files = []
    for filename in os.listdir(usb_path):
        file_path = os.path.join(usb_path, filename)
        if filename.lower().endswith('.txt') and os.path.isfile(file_path):
            txt_files.append(file_path)

    if not txt_files:
        print("U盘中没有txt文件。")
        return

    # 获取合并文件名
    merged_name = input("请输入合并后的文件名（例如 merged.txt）: ").strip()
    if not merged_name.endswith('.txt'):
        merged_name += '.txt'

    # 获取目标文件夹
    dest_folder = r'C:\Users\Administrator\Desktop\anchortagdata\comLog\log'
    os.makedirs(dest_folder, exist_ok=True)
    dest_path = os.path.join(dest_folder, merged_name)

    # 合并文件内容
    merged_content = []
    for file in sorted(txt_files):  # 按文件名排序
        try:
            with open(file, 'r', encoding='utf-8') as f:
                merged_content.append(f"=== {os.path.basename(file)} ===\n")
                merged_content.append(f.read() + '\n\n')
        except Exception as e:
            print(f"读取文件 {file} 失败: {e}")
            return

    # 写入目标文件
    try:
        with open(dest_path, 'w', encoding='utf-8') as f:
            f.writelines(merged_content)
    except Exception as e:
        print(f"写入目标文件失败: {e}")
        return

    print(f"文件已合并保存至: {dest_path}")

    print(f"\n警告：即将永久删除 {usb_path} 下的所有内容！")

    # 删除U盘内容
    for filename in os.listdir(usb_path):
        file_path = os.path.join(usb_path, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            print(f"删除 {file_path} 失败: {e}")

    print("操作完成，U盘内容已清空")

if __name__ == "__main__":
    merge_and_clean()